const pool = require('../config/db');
const fs = require('fs');
const path = require('path');

const fileController = {

    // 获取文件列表
    getFilesList: async (req, res) => {
        try {
            const userId = req.params.userId;
            const query = 'SELECT * FROM files WHERE user_id = ?';
            
            const [files] = await pool.query(query, [userId]);
            res.json(files);
        } catch (error) {
            res.status(500).json({ error: '获取文件列表失败' });
        }
    },

    // 下载文件
    downloadFile: async (req, res) => {
        try {
            const fileId = req.params.fileId;
            const query = 'SELECT * FROM files WHERE id = ?';
            
            const [files] = await pool.query(query, [fileId]);
            if (files.length === 0) {
                return res.status(404).json({ error: '文件不存在' });
            }
            
            res.download(files[0].file_path);
        } catch (error) {
            res.status(500).json({ error: '文件下载失败' });
        }
    },

    // 删除文件
    deleteFile: async (req, res) => {
        try {
            const fileId = req.params.fileId;
            const query = 'DELETE FROM files WHERE id = ?';
            
            await pool.query(query, [fileId]);
            res.json({ success: true });
        } catch (error) {
            res.status(500).json({ error: '文件删除失败' });
        }
    },

    // 分享文件
    shareFile: async (req, res) => {
        try {
            const { fileId, sharedBy, sharedWith } = req.body;
            const query = 'INSERT INTO shared_files (file_id, shared_by, shared_with) VALUES (?, ?, ?)';
            
            await pool.query(query, [fileId, sharedBy, sharedWith]);
            res.json({ success: true });
        } catch (error) {
            res.status(500).json({ error: '文件分享失败' });
        }
    },

    // 单文件上传
    uploadFile: async (req, res) => {
        try {
            if (!req.file) {
                return res.status(400).json({ error: '没有文件被上传' });
            }

            const { userId, folderId } = req.body;
            const file = req.file;

            // 使用原始文件名（解决中文乱码问题）
            const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');

            // 获取文件信息
            const fileInfo = {
                filename: originalName,
                file_path: file.path,
                file_size: file.size,
                file_type: file.mimetype,
                user_id: userId,
                folder_id: folderId || null
            };

            // 插入文件记录
            const [result] = await pool.query(
                'INSERT INTO files (filename, file_path, file_size, file_type, user_id, folder_id) VALUES (?, ?, ?, ?, ?, ?)',
                [fileInfo.filename, fileInfo.file_path, fileInfo.file_size, fileInfo.file_type, fileInfo.user_id, fileInfo.folder_id]
            );

            res.json({
                success: true,
                fileId: result.insertId,
                fileInfo
            });
        } catch (error) {
            console.error('文件上传错误:', error);
            res.status(500).json({ error: '文件上传失败', details: error.message });
        }
    },

    // 多文件上传
    uploadMultipleFiles: async (req, res) => {
        try {
            if (!req.files || req.files.length === 0) {
                return res.status(400).json({ error: '没有文件被上传' });
            }

            const { userId, folderId } = req.body;
            const uploadedFiles = [];

            for (const file of req.files) {
                // 使用原始文件名（解决中文乱码问题）
                const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');

                const fileInfo = {
                    filename: originalName,
                    file_path: file.path,
                    file_size: file.size,
                    file_type: file.mimetype.split('/')[0],
                    user_id: userId,
                    folder_id: folderId || null
                };

                // 插入文件记录
                const [result] = await pool.query(
                    'INSERT INTO files (filename, file_path, file_size, file_type, user_id, folder_id) VALUES (?, ?, ?, ?, ?, ?)',
                    [fileInfo.filename, fileInfo.file_path, fileInfo.file_size, fileInfo.file_type, fileInfo.user_id, fileInfo.folder_id]
                );

                uploadedFiles.push({
                    fileId: result.insertId,
                    ...fileInfo
                });
            }

            res.json({
                success: true,
                files: uploadedFiles
            });
        } catch (error) {
            console.error('文件上传错误:', error); // 记录错误以便调试
            res.status(500).json({ error: '文件上传失败', details: error.message });
        }
    },

    // 文件预览
    previewFile: async (req, res) => {
        try {
            const { fileId } = req.params;
            const { userId } = req.query;

            // 验证用户权限
            const [file] = await pool.query(
                `SELECT 
                    f.id,
                    f.filename,
                    f.file_path,
                    f.file_type,
                    f.file_size
                FROM files f
                WHERE f.id = ? AND (
                    f.user_id = ? OR 
                    EXISTS (
                        SELECT 1 FROM shared_files sf 
                        WHERE sf.file_id = f.id AND sf.shared_with = ?
                    )
                )`,
                [fileId, userId, userId]
            );

            if (file.length === 0) {
                return res.status(404).json({
                    error: '文件不存在或无权访问',
                    details: 'File not found or access denied'
                });
            }

            const fileInfo = file[0];
            const filePath = fileInfo.file_path;
            const fileType = fileInfo.file_type;

            // 检查文件是否存在
            if (!fs.existsSync(filePath)) {
                return res.status(404).json({
                    error: '文件不存在',
                    details: 'File not found on server'
                });
            }

            // 根据文件类型设置响应头
            switch (fileType.toLowerCase()) {
                case 'image':
                    // 图片直接显示
                    res.setHeader('Content-Type', `image/${path.extname(filePath).substring(1)}`);
                    fs.createReadStream(filePath).pipe(res);
                    break;

                case 'pdf':
                    // PDF 直接显示
                    res.setHeader('Content-Type', 'application/pdf');
                    fs.createReadStream(filePath).pipe(res);
                    break;

                case 'text':
                    // 文本文件直接显示内容
                    fs.readFile(filePath, 'utf8', (err, data) => {
                        if (err) {
                            return res.status(500).json({
                                error: '读取文件失败',
                                details: err.message
                            });
                        }
                        res.setHeader('Content-Type', 'text/plain; charset=utf-8');
                        res.send(data);
                    });
                    break;

                case 'video':
                    // 视频流式传输
                    const range = req.headers.range;
                    if (!range) {
                        res.status(400).json({ error: '需要 Range header' });
                        return;
                    }

                    const videoSize = fs.statSync(filePath).size;
                    const CHUNK_SIZE = 10 ** 6; // 1MB
                    const start = Number(range.replace(/\D/g, ''));
                    const end = Math.min(start + CHUNK_SIZE, videoSize - 1);

                    const contentLength = end - start + 1;
                    const headers = {
                        'Content-Range': `bytes ${start}-${end}/${videoSize}`,
                        'Accept-Ranges': 'bytes',
                        'Content-Length': contentLength,
                        'Content-Type': 'video/mp4',
                    };

                    res.writeHead(206, headers);
                    const videoStream = fs.createReadStream(filePath, { start, end });
                    videoStream.pipe(res);
                    break;

                case 'audio':
                    // 音频流式传输
                    res.setHeader('Content-Type', 'audio/mpeg');
                    fs.createReadStream(filePath).pipe(res);
                    break;

                default:
                    // 其他类型文件返回文件信息
                    res.json({
                        success: true,
                        message: '此文件类型不支持预览',
                        fileInfo: {
                            id: fileInfo.id,
                            filename: fileInfo.filename,
                            fileType: fileInfo.file_type,
                            fileSize: fileInfo.file_size
                        }
                    });
            }
        } catch (error) {
            console.error('文件预览错误:', error);
            res.status(500).json({
                error: '文件预览失败',
                details: error.message
            });
        }
    },

    // 重命名文件
    renameFile: async (req, res) => {
        try {
            const { fileId } = req.params;
            const { newName, userId } = req.body;

            // 参数验证
            if (!newName || !newName.trim()) {
                return res.status(400).json({
                    error: '新文件名不能为空',
                    details: 'New filename is required'
                });
            }

            // 检查文件是否存在并验证权限
            const [file] = await pool.query(
                'SELECT * FROM files WHERE id = ? AND user_id = ?',
                [fileId, userId]
            );

            if (file.length === 0) {
                return res.status(404).json({
                    error: '文件不存在或无权访问',
                    details: 'File not found or access denied'
                });
            }

            const oldFile = file[0];
            const oldPath = oldFile.file_path;
            
            // 获取文件扩展名
            const fileExt = path.extname(oldFile.filename);
            // 构建新文件名（保留原扩展名）
            const newFilename = newName.trim() + fileExt;

            // 检查同一文件夹下是否存在同名文件
            const [existingFile] = await pool.query(
                'SELECT id FROM files WHERE filename = ? AND folder_id = ? AND user_id = ? AND id != ?',
                [newFilename, oldFile.folder_id, userId, fileId]
            );

            if (existingFile.length > 0) {
                return res.status(400).json({
                    error: '同一文件夹下已存在同名文件',
                    details: 'File with same name already exists in this folder'
                });
            }

            // 构建新的文件路径
            const newPath = oldPath.replace(path.basename(oldPath), newFilename);

            // 开始事务
            const connection = await pool.getConnection();
            await connection.beginTransaction();

            try {
                // 更新数据库中的文件名和路径
                await connection.query(
                    'UPDATE files SET filename = ?, file_path = ? WHERE id = ?',
                    [newFilename, newPath, fileId]
                );

                // 重命名实际文件
                if (fs.existsSync(oldPath)) {
                    fs.renameSync(oldPath, newPath);
                }

                await connection.commit();

                res.json({
                    success: true,
                    message: '文件重命名成功',
                    fileInfo: {
                        id: fileId,
                        newFilename,
                        newPath
                    }
                });
            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('重命名文件错误:', error);
            res.status(500).json({
                error: '重命名文件失败',
                details: error.message
            });
        }
    },
};

module.exports = fileController;